<template>
  <!-- 完善信息 -->
  <Form
    class="xtx-form"
    ref="formCom"
    :validation-schema="schema"
    v-slot="{ errors }"
    autocomplete="off"
  >
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field
          :class="{ err: errors.account }"
          v-model="form.account"
          name="account"
          class="input"
          type="text"
          placeholder="请输入用户名"
        />
      </div>
      <div v-if="errors.account" class="error">{{ errors.account }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          :class="{ err: errors.mobile }"
          v-model="form.mobile"
          name="mobile"
          class="input"
          type="text"
          placeholder="请输入手机号"
        />
      </div>
      <div v-if="errors.mobile" class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          v-model="form.code"
          name="code"
          class="input"
          type="text"
          placeholder="请输入验证码"
        />
        <span @click="send(formCom)" class="code">{{
          time === 0 ? '发送验证码' : `${time}秒后发送`
        }}</span>
      </div>
      <div v-if="errors.code" class="error">{{ errors.code }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          :class="{ err: errors.password }"
          v-model="form.password"
          name="password"
          class="input"
          type="password"
          placeholder="请输入密码"
        />
      </div>
      <div v-if="errors.password" class="error">{{ errors.password }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          :class="{ err: errors.rePassword }"
          v-model="form.rePassword"
          name="rePassword"
          class="input"
          type="password"
          placeholder="请确认密码"
        />
      </div>
      <div v-if="errors.rePassword" class="error">{{ errors.rePassword }}</div>
    </div>
    <a @click="submit(formCom)" href="javascript:;" class="submit">立即提交</a>
  </Form>
</template>

<script>
import { ref, reactive, onUnmounted } from 'vue'
import { Field, Form } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import { useIntervalFn } from '@vueuse/core'
import { message } from '../../../components/library/message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: { Field, Form },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    // 1. 表单校验 多两个校验：用户名是否存在，再次输入密码是否一致
    // 2. 发送短信验证码：接口API定义
    // 3. 完善信息

    // 表单数据对象
    const form = reactive({
      account: '',
      password: '',
      mobile: '',
      code: '',
      rePassword: ''
    })

    const formCom = ref(null)
    const time = ref(0)
    const { pause, resume } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      { immediate: false }
    )
    onUnmounted(() => {
      pause()
    })
    // 发送验证码
    // 1.1 绑定发送验证码按钮点击事件
    // 1.2 校验手机号，如果成功才去发送短信（定义API），请求成功开启60s的倒计时，不能再次点击，倒计时结束恢复
    // 1.3 如果失败，失败的校验样式显示出来
    const send = async (formEl) => {
      const valid = formEl.validate()
      if (valid) {
        if (form.mobile) {
          // 通过倒计时没有结束直接退出
          if (time.value !== 0) return
          try {
            // 发送短信验证码
            await userQQPatchCode(form.mobile)
            // 发送成功后提示
            message({ type: 'success', message: '发送成功' })
            // 重置倒计时秒数
            time.value = 60
            // 启动定时器
            resume()
          } catch (e) {
            message({
              type: 'error',
              message: e.response.data.message || '登录失败'
            })
          }
        }
      }
    }

    // 完善信息
    const store = useStore()
    const router = useRouter()
    const submit = async (formEl) => {
      // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
      const valid = formEl.validate()
      if (valid) {
        // 发送请求
        try {
          const { result } = await userQQPatchLogin({
            unionId: props.unionId,
            ...form
          })
          message({ type: 'success', message: '登录成功' })
          store.commit('user/setUser', result)
          router.push('/')
        } catch (e) {
          message({
            type: 'error',
            message: e.response.data.message || '登录失败'
          })
        }
      }
    }
    return { form, schema, formCom, time, send, submit }
  }
}
</script>
<style scoped lang="less">
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
